package ru.hh.school;

import java.util.*;

public class Room {
    private final String name;
    private final Set<User> users;
    private final int id;

    public Room(int id, String name) {
        this.id = id;
        this.name = name;
        this.users = new HashSet<User>();
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void addUser(User user) {
        synchronized (users) {
            users.add(user);
        }
    }

    public void delUser(User user) {
        synchronized (users) {
            users.remove(user);
        }
    }

    public void send(String message) {
        List<User> shuffledUsers;
        synchronized (users) {
            shuffledUsers = new ArrayList<User>(users);
        }
        Collections.shuffle(shuffledUsers);
        for (User user : shuffledUsers) {
            user.sendMessage(message);
        }
    }

    public void send(String message, User exclude) {
        List<User> shuffledUsers;
        synchronized (users) {
            shuffledUsers = new ArrayList<User>(users);
        }
        Collections.shuffle(shuffledUsers, new Random(System.currentTimeMillis()));
        for (User user : shuffledUsers) {
            if (!user.equals(exclude)) {
                user.sendMessage(message);
            }
        }
    }

    public String toString() {
        return getName();
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Room room = (Room) o;

        if (id != room.id) return false;
        if (name != null ? !name.equals(room.name) : room.name != null) return false;
        if (users != null ? !users.equals(room.users) : room.users != null) return false;

        return true;
    }

    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (users != null ? users.hashCode() : 0);
        result = 31 * result + id;
        return result;
    }
}
